// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import config from "../config/config";

const { ccclass, property } = cc._decorator;

@ccclass
export default class AdManage extends cc.Component {

    public static instance: AdManage = null;

    n_platformApi: any = null;
    n_systemInfo: any = null;
    n_viodeAd: any = null;
    n_bannerAd: any = null;
    n_CustomAd: any = null;
    n_blockAd: any = null;

    onLoad() {
        AdManage.instance = this;
    }

    start() {
        this.init();
    }

    init() {
        if (config.gameType == "wx") {
            this.n_platformApi = window["wx"];
        } else if (config.gameType == "vivo") {
            this.n_platformApi = window["qg"];
        } else if (config.gameType == "QQ") {
            this.n_platformApi = window["qq"];
        }
        if (config.gameType != "") {
            this.n_systemInfo = this.n_platformApi.getSystemInfoSync();
        }
    }

    /**
     * 激励视频广告
     * @param id 
     * @param callback 
     */
    initRewardedVideoAd(id: string, callback: Function = null) {
        if (!id || id == "") return;
        if (config.gameType == "wx") {
            let version = this.compareVersion(this.n_systemInfo.SDKVersion, "2.6.0");
            if (version) {
                this.n_platformApi.showLoading({
                    title: "请稍等..."
                })
                if (!this.n_viodeAd) {
                    this.n_viodeAd = this.n_platformApi.createRewardedVideoAd({
                        adUnitId: id
                    })
                }
                this.n_viodeAd.load()
                    .then(() => {
                        console.log("激励视频加载成功");
                    })
                    .catch((err: any) => {
                        this.n_platformApi.hideLoading();
                        console.log(err, "激励视频加载失败");
                    })
                this.n_viodeAd.onLoad(() => {
                    this.n_platformApi.hideLoading();
                    console.log("激励视频拉取成功");
                    this.n_viodeAd.show()
                        .then().catch((err: any) => {
                            console.log(err, "激励视频显示失败");
                            this.n_viodeAd.load()
                                .then(() => {
                                    console.log("激励视频加载成功");
                                })
                                .catch((err: any) => {
                                    this.n_platformApi.showToast({
                                        title: "视频显示失败"
                                    })
                                    console.log(err, "激励视频加载失败");
                                })
                        })
                })
                this.n_viodeAd.onError((err: any) => {
                    this.n_platformApi.hideLoading();
                    console.log(err, "激励视频拉取失败");
                })
                this.n_viodeAd.onClose((res: any) => {
                    if (res && res.isEnded) {
                        callback && callback(1);
                    } else {
                        this.n_platformApi.showToast({
                            title: "中途关闭"
                        })
                        callback && callback(0);
                    }
                })
            }
        } else if (config.gameType == "vivo") {
            this.version(() => {
                this.n_platformApi.showLoading({
                    message: "请稍等..."
                })
                if (this.n_viodeAd == null) {
                    this.n_viodeAd = this.n_platformApi.createRewardedVideoAd({
                        posId: id
                    })
                }
                this.n_viodeAd.onError(err => {//拉取失败
                    this.n_platformApi.hideLoading();
                    cc.audioEngine.setMusicVolume(config.bgSound);
                    console.log(JSON.stringify(err), "获取失败");
                    callback(0);
                    this.n_platformApi.showToast({
                        message: '获取失败',
                    })
                })
                this.n_viodeAd.load()
                    .then(() => {
                        this.n_platformApi.hideLoading();
                        this.n_viodeAd.show();
                    })
                    .catch((err: any) => {
                        cc.audioEngine.setMusicVolume(config.bgSound);
                        this.n_platformApi.hideLoading();
                        console.log(JSON.stringify(err), "激励视频拉取失败");
                        this.n_platformApi.showToast({
                            message: '视频拉取失败',
                        })
                    })
                this.n_viodeAd.onClose((res: any) => {
                    this.n_viodeAd.offClose();
                    cc.audioEngine.setMusicVolume(config.bgSound);
                    if (res && res.isEnded) {
                        callback(1);
                    } else {
                        callback(2);
                        this.n_platformApi.showToast({
                            message: "中途退出",
                        })
                    }
                })
            }, "1041")
        } else if (config.gameType == "QQ") {
            this.n_platformApi.showLoading({
                title: "请稍等..."
            })
            this.n_viodeAd = this.n_platformApi.createRewardedVideoAd({
                adUnitId: id
            })
            this.n_viodeAd.load()
                .then(() => {
                    this.n_platformApi.hideLoading();
                    this.n_viodeAd.show();
                })
                .catch((err) => {
                    this.n_platformApi.hideLoading();
                    console.log(err, "激励广告拉取失败");
                    this.n_platformApi.showToast({
                        title: '视频拉取失败',
                    })
                })
            this.n_viodeAd.onError((err) => {
                this.n_platformApi.hideLoading();
                console.log(err, "激励广告加载失败");
            })
            this.n_viodeAd.onClose((res: any) => {
                this.n_viodeAd.offClose();
                if (res && res.isEnded) {
                    callback && callback(1);
                } else {
                    callback && callback(2);
                    this.n_platformApi.showToast({
                        title: "中途退出",
                    })
                }
            })
        }
    }
    /**
     * banner广告
     * @param id 
     */
    initBannerAd(id: string) {
        if (!id || id == "") return;
        if (config.gameType == "wx") {
            let version = this.compareVersion(this.n_systemInfo.SDKVersion, "2.0.4");
            if (version) {
                this.n_bannerAd = this.n_platformApi.createBannerAd({
                    adUnitId: id,
                    style: {
                        top: cc.winSize.height - 118,
                        left: 0,
                        width: cc.winSize.width,
                        height: 118
                    }
                })
                this.n_bannerAd.onResize((res: any) => {
                    this.n_bannerAd.style.width = res.width;
                    this.n_bannerAd.style.height = res.height;
                    this.n_bannerAd.style.top = this.n_systemInfo.windowHeight - res.height;
                })
                this.n_bannerAd.onLoad(e => {
                    if (!config.showBanner) {
                        this.n_bannerAd.hide();
                        this.n_bannerAd.destroy();
                        return;
                    }
                    this.n_bannerAd.show()
                        .catch((err: any) => {
                            console.log(err, "banner广告显示失败");
                        });
                })
                this.n_bannerAd.onError(err => {
                    console.log(err, "banner加载失败");
                })
            } else {
                this.n_platformApi.showToast({
                    title: '版本过低',
                })
            }
        } else if (config.gameType == "vivo") {
            this.version(() => {
                this.n_bannerAd = this.n_platformApi.createBannerAd({
                    posId: id,
                })
                this.n_bannerAd.onLoad(res => {
                    if (!config.showBanner) {
                        // this.n_bannerAd.hide();
                        this.n_bannerAd.destroy();
                        return;
                    }
                    this.n_bannerAd.show()
                        .catch((err: any) => {
                            console.log(JSON.stringify(err), "banner显示失败");
                        })
                })
                this.n_bannerAd.onError(err => {
                    console.log(JSON.stringify(err), "banner加载失败");
                })
                this.n_bannerAd.onClose(() => {
                    config.showBanner = false;
                    this.n_bannerAd.destroy();
                })
            }, "1031")
        } else if (config.gameType == "QQ") {
            this.n_bannerAd = this.n_platformApi.createBannerAd({
                adUnitId: id,
                adIntervals: 30,
                style: {
                    left: 0,
                    top: 0,
                    width: 100,
                    height: 84
                }
            })
            this.n_bannerAd.onResize((res) => {
                this.n_bannerAd.style.width = res.width;
                this.n_bannerAd.style.height = res.height;
                let scl = 1;
                if(this.n_systemInfo.screenHeight / this.n_systemInfo.screenWidth >= 2){
                    scl = 2;
                }
                this.n_bannerAd.style.top = this.n_systemInfo.screenHeight - res.height * scl;
                this.n_bannerAd.style.left = (this.n_systemInfo.screenWidth - res.width) / 2;
            })
            this.n_bannerAd.onLoad(res => {
                if (!config.showBanner) {
                    this.n_bannerAd.destroy();
                    return;
                }
                this.n_bannerAd.show()
                    .catch((err: any) => {
                        console.log(JSON.stringify(err), "banner显示失败");
                    })
            })
            this.n_bannerAd.onError((res)=>{
                console.log(JSON.stringify(res), "banner广告加载失败");
            })
        }
    }
    /**
     * 插屏广告
     * @param id 
     */
    initInterstitialAd(id: string) {
        if (config.gameType == "vivo") {

        }
    }
    /**
     * 原生广告
     * @param id 
     */
    initCustomAd(id: string, node: cc.Node, callback: Function = null) {
        if (!id || id == "") return node.active = false;
        if (config.gameType == "vivo") {
            this.version((date) => {
                this.n_platformApi.showLoading({
                    message: "请稍等..."
                })
                if (date === 1 && node != null) {
                    // node.active = false;
                    this.n_platformApi.hideLoading();
                    this.n_platformApi.showToast({
                        message: '版本过低'
                    })
                } else {
                    this.n_CustomAd = this.n_platformApi.createNativeAd({
                        adUnitId: id
                    })
                    this.n_CustomAd.load();

                    this.n_CustomAd.onLoad((res: any) => {
                        this.n_platformApi.hideLoading();
                        // console.log(JSON.stringify(res), "原生广告加载成功");
                        config.qg_createNativeAd = res.adList[0];
                        this.n_CustomAd.reportAdShow({ adId: res.adList[0].adId.toString() });
                        // this.n_CustomAd.reportAdClick({ adId: res.adList[0].adId.toString() }); 
                        callback && callback(res.adList[0], this.n_CustomAd);
                    })
                    this.n_CustomAd.onError((res: any) => {
                        this.n_platformApi.hideLoading();
                        callback(0, null);
                        // node.active = false;
                        this.n_platformApi.showToast({
                            message: '广告加载失败'
                        })
                    })
                }

            }, "1053")
        }
    }

    /**
     * 判断版本号是否达标
     * @param curV 当前的版本
     * @param reqV 最低版本
     */
    compareVersion(curV: string, reqV: string) {
        let lVersion = curV.split("."),
            sVersion = reqV.split('.'),
            lVersionNum = parseInt(lVersion[0]) * 1000000 + parseInt(lVersion[1]) * 10000 + parseInt(lVersion[2]) * 100,
            sVersionNum = parseInt(sVersion[0]) * 1000000 + parseInt(sVersion[1]) * 10000 + parseInt(sVersion[2]) * 100;
        if (lVersionNum < sVersionNum) {
            return false
        }
        return true
    }
    version(callBack: Function, version: string) {
        if (config.gameType == "vivo") {
            this.n_systemInfo = this.n_platformApi.getSystemInfoSync();
            if (this.n_systemInfo.platformVersionCode >= parseInt(version)) {
                callBack();
            } else {
                callBack(1);
                this.n_platformApi.showToast({
                    message: '版本过低',
                })
            }
        }
    }
    /**创建QQ盒子广告 */
    initQQcreateAppBox() {
        if (config.gameType != "QQ" || this.n_platformApi.createAppBox == null) return;
        let appBox = this.n_platformApi.createAppBox({
            adUnitId: "39c54e84be08c99102a703be7bda147f"
        })
        appBox.load()
            .then(() => {
                appBox.show()
                    .catch((err) => {
                        console.log(JSON.stringify(err), "显示盒子广告失败");
                    })
            })
            .catch((err) => {
                console.log(JSON.stringify(err), "拉取盒子广告失败");
            })
        appBox.onClose((data) => {
            appBox.destroy();
        })
    }
    /**创建QQ积木广告 */
    initQQcreateBlockAd(orientation: string) {
        if (this.n_platformApi.createBlockAd == null) return;
        if (this.n_blockAd != null) {
            this.n_blockAd.destroy();
        }
        this.n_blockAd = this.n_platformApi.createBlockAd({
            adUnitId: "9df7398507c582006dafe74eaf779c5a",
            size: 5,
            orientation: orientation,
            style: {
                left: 16,
                top: 16
            },
        })
        this.n_blockAd.onResize((res) => {
            // this.blockAd.style.left = (config.winSize.width - res.width) / 2;
            this.n_blockAd.style.top = this.n_systemInfo.screenHeight / 9;
        })
        this.n_blockAd.onLoad(() => {
            this.n_blockAd.show()
                .then((res) => {
                    console.log(JSON.stringify(res), "积木广告显示成功");
                })
                .catch((err) => {
                    console.log(JSON.stringify(err), "积木广告显示失败");
                })
        })
        this.n_blockAd.onError((err) => {
            console.log(JSON.stringify(err), "积木广告加载失败");
        })
    }
}
